package com.TextFormat;


import java.lang.reflect.Method;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import com.Managers.LogManagerClass;


public class ExpandableTextView {

    private static final String TAG = "ExpandableTextView";

    static public void expandOrCollapse(View view2Expand, View view2Measure, int collapsedHeight) {

        if (view2Expand.getHeight() < collapsedHeight)
            return;
        int measuredHeight = measureViewHeight(view2Expand, view2Measure);
        if (measuredHeight < collapsedHeight)
            measuredHeight = collapsedHeight;
        final int startHeight = view2Expand.getHeight();
        final int finishHeight = startHeight <= collapsedHeight ? measuredHeight
                    : collapsedHeight;
        view2Expand.startAnimation(new ExpandAnimation(view2Expand, startHeight, finishHeight));
    }

    public static int measureViewHeight(View view2Expand, View view2Measure) {

        try {
            Method m = view2Measure.getClass().getDeclaredMethod("onMeasure", int.class, int.class);
            m.setAccessible(true);
            m.invoke(view2Measure, MeasureSpec.makeMeasureSpec(view2Expand.getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int measuredHeight = view2Measure.getMeasuredHeight();
            return measuredHeight;
        }
        catch (Exception x) {
            Log.e(TAG + ": ", x.getMessage());
            LogManagerClass.writeLog(TAG + ": " + x.getMessage());
            return -1;
        }

    }

    static class ExpandAnimation extends Animation {

        private final int _finishHeight;

        private final int _startHeight;

        private final View _view;

        public ExpandAnimation(View view, int startHeight,
                    int finishHeight) {

            _view = view;
            _startHeight = startHeight;
            _finishHeight = finishHeight;
            setDuration(220);
        }

        @Override
        public boolean willChangeBounds() {

            return true;
        }

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {

            final int newHeight = (int) ((_finishHeight - _startHeight)
                        * interpolatedTime + _startHeight);
            _view.getLayoutParams().height = newHeight;
            _view.requestLayout();
        }
    };
}
